<template>
  <div class="contest-list">
    <div class="header-section">
      <h2>近期 · AI创作大赛</h2>
      <p class="subtitle">发现最新的AI创作竞赛机会</p>
    </div>
    <!-- 调试信息 -->
    <!-- <div v-if="true" style="background: #333; color: #fff; padding: 10px; margin: 10px 0; border-radius: 5px; font-family: monospace; font-size: 12px;">
      <div>调试信息：</div>
      <div>contests.value长度: {{ contests.value?.length || 0 }}</div>
      <div>filteredContests长度: {{ filteredContests?.length || 0 }}</div>
      <div>loading状态: {{ loading }}</div>
      <div>isLoading状态: {{ isLoading }}</div>
      <div>contests数据: {{ JSON.stringify(contests.value, null, 2) }}</div>
    </div> -->
    
    <div class="contests-grid">
      <!-- 加载状态 -->
      <div v-if="loading || isLoading" class="loading-message">
        <p>正在加载竞赛列表...</p>
      </div>
      
      <!-- 无数据状态 -->
      <div v-else-if="!filteredContests || filteredContests.length === 0" class="no-data-message">
        <p>暂无竞赛数据</p>
        <button @click="loadContests" class="retry-btn">重新加载</button>
      </div>
      
      <!-- 竞赛列表 -->
      <div v-else v-for="contest in filteredContests" :key="contest.id" class="contest-card">
        <div class="card-header">
          <span class="status-badge" :class="getStatusClass(contest.status)">{{ getStatusText(contest.status) }}</span>
        </div>
        <div class="card-content">
          <h3 class="contest-title">{{ contest.title }}</h3>
          <div class="contest-info">
            <div class="date-info">
              <span class="label">大赛时间：</span>
              <span class="value">{{ formatContestDate(contest) }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <button class="view-btn" @click="viewContest(contest.id)">查看详情</button>
        </div>
      </div>
    </div>
    
    <!-- 竞赛详情弹窗 -->
    <ContestDetail 
      :visible="showDetailModal" 
      :contest-id="selectedContestId"
      @close="closeDetailModal"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useContestStore } from '../stores/contest';
import ContestDetail from './ContestDetail.vue';

// 初始化store和响应式数据
const contestStore = useContestStore();
const searchQuery = ref('');
const selectedStatus = ref('all');
const sortBy = ref('date');
const loading = ref(false);
const showDetailModal = ref(false);
const selectedContestId = ref(null);

    // 从store获取竞赛数据
    const contests = computed(() => contestStore.contests);
    const isLoading = computed(() => contestStore.loading);

    // 过滤和排序竞赛
    const filteredContests = computed(() => {
      // 确保 contests.value 是数组
      let filtered = Array.isArray(contests.value) ? contests.value : [];
      
      // 按搜索关键词过滤
      if (searchQuery.value) {
        filtered = filtered.filter(contest => 
          contest.title && contest.title.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      }
      
      // 按状态过滤
      if (selectedStatus.value !== 'all') {
        filtered = filtered.filter(contest => contest.status === selectedStatus.value);
      }
      
      // 排序
      if (sortBy.value === 'date') {
        filtered.sort((a, b) => new Date(b.startDate || b.date) - new Date(a.startDate || a.date));
      } else if (sortBy.value === 'title') {
        filtered.sort((a, b) => a.title.localeCompare(b.title));
      }
      
      return filtered;
    });

    /**
     * 获取状态对应的CSS类名
     * @param {string} status - 竞赛状态
     * @returns {string} CSS类名
     */
    const getStatusClass = (status) => {
      switch (status) {
        case 'active':
        case '进行中': 
          return 'status-active';
        case 'upcoming':
        case '即将开始': 
          return 'status-upcoming';
        case 'ended':
        case '已结束': 
          return 'status-ended';
        default: 
          return 'status-ended';
      }
    };

    /**
     * 获取状态显示文本
     * @param {string} status - 竞赛状态
     * @returns {string} 显示文本
     */
    const getStatusText = (status) => {
      switch (status) {
        case 'active': return '进行中';
        case 'upcoming': return '即将开始';
        case 'ended': return '已结束';
        default: return status || '已结束';
      }
    };

    /**
     * 格式化竞赛时间
     * @param {Object} contest - 竞赛对象
     * @returns {string} 格式化的时间字符串
     */
    const formatContestDate = (contest) => {
      if (contest.startDate && contest.endDate) {
        const start = new Date(contest.startDate).toLocaleDateString('zh-CN');
        const end = new Date(contest.endDate).toLocaleDateString('zh-CN');
        return `${start} - ${end}`;
      } else if (contest.date) {
        return new Date(contest.date).toLocaleDateString('zh-CN');
      } else if (contest.startTime && contest.endTime) {
        const start = new Date(contest.startTime).toLocaleDateString('zh-CN');
        const end = new Date(contest.endTime).toLocaleDateString('zh-CN');
        return `${start} - ${end}`;
      }
      return '时间待定';
    };

    /**
     * 查看竞赛详情
     * @param {string|number} contestId - 竞赛ID
     */
    const viewContest = async (contestId) => {
      try {
        // 先获取竞赛详情数据
        await contestStore.fetchContestById(contestId);
        
        // 设置选中的竞赛ID并显示详情弹窗
        selectedContestId.value = contestId;
        showDetailModal.value = true;
        
        console.log('查看竞赛详情:', contestId);
      } catch (error) {
        console.error('获取竞赛详情失败:', error);
        alert('获取竞赛详情失败，请稍后重试');
      }
    };
    
    /**
     * 关闭详情弹窗
     */
    const closeDetailModal = () => {
      showDetailModal.value = false;
      selectedContestId.value = null;
    };

    /**
     * 参加竞赛
     * @param {string|number} contestId - 竞赛ID
     */
    const joinContest = async (contestId) => {
      try {
        const success = await contestStore.joinContest(contestId);
        if (success) {
          alert('参加竞赛成功！');
        } else {
          alert('参加竞赛失败，请重试');
        }
      } catch (error) {
        console.error('参加竞赛失败:', error);
        alert('参加竞赛失败，请重试');
      }
    };

    /**
     * 加载竞赛列表
     */
    const loadContests = async () => {
      loading.value = true;
      try {
        console.log('开始加载竞赛列表...');
        const result = await contestStore.fetchContests({
          page: 1,
          pageSize: 20,
          status: selectedStatus.value !== 'all' ? selectedStatus.value : undefined
        });
        console.log('竞赛列表加载结果:', result);
        console.log('Store中的竞赛数据:', contestStore.contests);
        console.log('计算属性contests:', contests.value);
        console.log('过滤后的竞赛:', filteredContests.value);
      } catch (error) {
        console.error('获取竞赛列表失败:', error);
        // 提供默认竞赛数据用于测试
        contestStore.contests = [
          {
            id: 1,
            title: 'AI创意设计大赛',
            status: 'active',
            startDate: '2024-01-01',
            endDate: '2024-03-01',
            participants: 150
          },
          {
            id: 2,
            title: 'AI编程挑战赛',
            status: 'upcoming',
            startDate: '2024-02-01',
            endDate: '2024-04-01',
            participants: 89
          }
        ];
        console.log('使用默认竞赛数据:', contestStore.contests);
      } finally {
        loading.value = false;
      }
    };

    /**
     * 搜索竞赛
     */
    const searchContests = async () => {
      if (searchQuery.value.trim()) {
        loading.value = true;
        try {
          await contestStore.fetchContests({
            page: 1,
            pageSize: 20,
            search: searchQuery.value.trim(),
            status: selectedStatus.value !== 'all' ? selectedStatus.value : undefined
          });
        } catch (error) {
          console.error('搜索竞赛失败:', error);
        } finally {
          loading.value = false;
        }
      } else {
        loadContests();
      }
    };

    /**
     * 状态变化处理
     */
    const onStatusChange = () => {
      loadContests();
    };

// 组件挂载时获取竞赛数据
onMounted(() => {
  loadContests();
});
</script>

<style scoped>
.contest-list {
  padding: 20px 0;
}

.header-section {
  text-align: center;
  margin-bottom: 40px;
}

.header-section h2 {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 10px;
}

.subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
}

.contests-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 25px;
  margin-top: 30px;
}

.contest-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.contest-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
}

.card-header {
  padding: 20px 20px 0;
  display: flex;
  justify-content: flex-end;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-ended {
  background: rgba(156, 163, 175, 0.2);
  color: #9ca3af;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

.status-ongoing {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-upcoming {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.card-content {
  padding: 0 20px 20px;
}

.contest-title {
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 15px;
  line-height: 1.4;
  min-height: 50px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.contest-info {
  margin-bottom: 20px;
}

.date-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.label {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
  margin-right: 8px;
}

.value {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
}

.card-footer {
  padding: 0 20px 20px;
}

.view-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

@media (max-width: 768px) {
  .header-section h2 {
    font-size: 24px;
  }
  
  .contests-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .contest-card {
    margin: 0 10px;
  }
  
  .contest-title {
    font-size: 16px;
    min-height: 40px;
  }
}

/* 加载和无数据状态样式 */
.loading-message,
.no-data-message {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 20px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.loading-message p,
.no-data-message p {
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  margin-bottom: 20px;
}

.retry-btn {
  padding: 10px 20px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

@media (max-width: 480px) {
  .contests-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .contest-card {
    margin: 0 5px;
  }
  
  .card-header,
  .card-content,
  .card-footer {
    padding-left: 15px;
    padding-right: 15px;
  }
}
</style>